package com.achievement.controller;

import com.achievement.domain.dto.honor.HonorApplyBookDTO;
import com.achievement.domain.entity.BookEntity;
import com.achievement.domain.entity.HonorApplyBookEntity;
import com.achievement.domain.param.honor.HonorApplyBookParam;
import com.achievement.domain.vo.honor.HonorApplyBookExcelVO;
import com.achievement.domain.vo.honor.HonorApplyBookReviewVO;
import com.achievement.service.IExpertReviewService;
import com.achievement.service.IHonorApplyBookService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.annotation.Anonymous;
import com.common.annotation.Log;
import com.common.api.ApprovalApi;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.common.core.page.TableDataInfo;
import com.common.enums.BusinessType;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.poi.ExcelUtil;
import com.flowable.service.IFlowTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "成果获奖-获奖申报")
@RestController
@RequestMapping("/achievement/honorApplyBook")
public class HonorApplyBookController extends BaseController {

    @Autowired
    IHonorApplyBookService honorApplyBookService;

    @Autowired
    IExpertReviewService expertReviewService;
    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private ApprovalApi approvalApi;
    private final static String module_name = "申报获奖";
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:list')")
    @ApiOperation("申报材料列表")
    @GetMapping("/list")
    public TableDataInfo list(HonorApplyBookParam param)
    {
        startPage();
        List<HonorApplyBookReviewVO> list = honorApplyBookService.listByPage(param);
        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        for (HonorApplyBookReviewVO u:list) {
            String processInstanceId = u.getProcessInstanceId();
            if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                u.setTaskId(instanceTaskMap.get(processInstanceId));
                u.setIsAuditor(flowTaskService.IsAuditor(SecurityUtils.getLoginUser().getUser().getUserId().toString(),u.getProcessInstanceId()));
            } else {
                u.setIsAuditor(false);
            }
        }
        return getDataTable(list);
    }
    /**
     * 左上方统计 全部 学校通过 学校退回 待审核
     * @param param 检索参数
     * @return AjaxResult
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:list-statistics')")
    @ApiOperation("获取申报计划左上方分组")
    @GetMapping(value = "/list-statistics")

    public AjaxResult listStatistics( HonorApplyBookParam param)
    {
        List<HashMap<String, Integer>> list =honorApplyBookService.listStatistics(param);
        return success(list);
    }

    /**
     * 获奖成果导出
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:export')")
    @ApiOperation("申报材料导出")
    @Log(title = "申报材料导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")

    public void export(HttpServletResponse response,@RequestBody Map<String,Object> requestMap)
    {
        HonorApplyBookParam param = JSONObject.parseObject(JSONObject.toJSONString(requestMap), HonorApplyBookParam.class);
        List<String> selectedColumns = (List<String>) requestMap.get("selectedColumns");
        List<HonorApplyBookExcelVO> list = honorApplyBookService.lisExcelByPage(param);
        ExcelUtil<HonorApplyBookExcelVO> util = new ExcelUtil<>(HonorApplyBookExcelVO.class);
        util.showColumn(selectedColumns.toArray(new String[0]));
        util.exportExcelByOrder(response, list, "申报材料列表",selectedColumns.toArray(new String[0]));
    }

    /**
     * 获取申报材料详细信息
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:query')")
    @ApiOperation("获取申报材料详细信息")
    @GetMapping(value = "/{id}")

    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(honorApplyBookService.getInfoById(id));
    }


    /**
     * 新增申报材料
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:add')")
    @ApiOperation("新增申报材料")
    @Log(title = "新增申报材料", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody HonorApplyBookDTO dto)
    {
        dto.setApplierId(SecurityUtils.getUserId().toString());
        dto.setApplierName(SecurityUtils.getNickName());
        return honorApplyBookService.addHonorApplyBookAndHonorApplyBookMember(dto);
    }
    /**
     * 修改申报材料
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:update')")
    @ApiOperation("修改申报材料")
    @Log(title = "修改申报材料", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update")
    public AjaxResult edit(@RequestBody HonorApplyBookDTO dto)
    {
        return honorApplyBookService.updateHonorApplyBookAndHonorApplyBookMember(dto);
    }

    /**
     * 删除申报材料
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:remove')")
    @ApiOperation("删除申报材料")
    @Log(title = "删除申报材料", businessType = BusinessType.DELETE)
    @DeleteMapping("/del/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        return toAjax(honorApplyBookService.batchRemove(ids));
    }

    /**
     * 管理员审核 通过、退回、作废
     */
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:check')")
    @ApiOperation("管理员审核 通过Checkstatus=2、退回Checkstatus=4、作废Checkstatus=-2  -1暂存状态")
    @PutMapping(value = "/check")
    public AjaxResult check(@RequestBody HonorApplyBookDTO dto)
    {
        return toAjax(honorApplyBookService.updateHonorApplyBookCheckStatus(dto.getId(),dto.getCheckstatus()));
    }
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:honorApplyBookHistory')")
    @ApiOperation("历史申报")
    @GetMapping("/honorApplyBookHistory")
    public TableDataInfo honorApplyBookHistory(HonorApplyBookParam param)
    {
        startPage();
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey(); //当前角色
        if("biz_kyms".equals(currentRoleKey)||currentRoleKey.equals("biz_kycgly")){
            List<HonorApplyBookReviewVO> list = honorApplyBookService.listByPage(param);
            //获取当前用户所有的代办列表
            Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
            for (HonorApplyBookReviewVO u:list) {
                String processInstanceId = u.getProcessInstanceId();
                if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                    u.setTaskId(instanceTaskMap.get(processInstanceId));
                    u.setIsAuditor(flowTaskService.IsAuditor(SecurityUtils.getLoginUser().getUser().getUserId().toString(),u.getProcessInstanceId()));
                } else {
                    u.setIsAuditor(false);
                }
            }
            return getDataTable(list);
        }else{
            param.setApplierId(SecurityUtils.getUserId().toString());
            List<HonorApplyBookReviewVO> list = honorApplyBookService.listByPage(param);
            return getDataTable(list);
        }
    }
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:revokeHonorApplyBook')")
    @ApiOperation("科研人员-申报中-撤销申报")
    @PutMapping("/revokeHonorApplyBook")
    public AjaxResult revokeHonorApplyBook(@RequestBody HonorApplyBookDTO dto)
    {
        return toAjax(honorApplyBookService.updateHonorApplyBookCheckStatus(dto.getId(),dto.getCheckstatus()));
    }
    @PreAuthorize("@ss.hasPermi('achievement:honorApplyBook:updateHonorApplyBookHonorState')")
    @ApiOperation("科研秘书-管理员-申报结束-设置获奖")
    @PutMapping("/updateHonorApplyBookHonorState")
    public AjaxResult updateHonorApplyBookHonorState(@RequestBody HonorApplyBookDTO dto)
    {
        return toAjax(honorApplyBookService.updateHonorApplyBookHonorState(dto));
    }

}
